package com.warehouse.controller;


import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.warehouse.entity.po.*;
import com.warehouse.entity.pojo.Colour;
import com.warehouse.entity.pojo.Detailed;
import com.warehouse.entity.pojo.FileZipPO;
import com.warehouse.entity.vo.DetailedVO;
import com.warehouse.result.Result;
import com.warehouse.service.DetailedService;
import com.warehouse.service.impl.DetailedServiceImpl;
import com.warehouse.util.GetQRCode;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.util.StringUtil;
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipOutputStream;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 详细信息 前端控制器
 * </p>
 *
 * @author 卓汉杰
 * @since 2021-05-07
 */
@Api("详细信息")
@Slf4j
@CrossOrigin
@RestController
@RequestMapping("/detailed")
public class DetailedController {

    @Autowired
    DetailedServiceImpl detailedService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;


    @ApiOperation(value = "添加记录")
    @PostMapping("/insert")
    @ResponseBody
    public Result insert(@RequestBody AddDetailedPO addDetailedPO) throws IOException {

        if (addDetailedPO == null) {
            return new Result(null, Result.NULL, "对象为空");
        }


        // 创建详细信息对象
        Detailed detailed = new Detailed();

        // 将po转为pojo
        BeanUtils.copyProperties(addDetailedPO, detailed);

        Date date = new Date();
        SimpleDateFormat sd = new SimpleDateFormat("yyyyMMdd");
        String key = sd.format(date);

        String programming = "";

        log.info("key"+key);

        // 判断key是否存在
        String val = stringRedisTemplate.opsForValue().get(key);
        log.info("val="+val);
        if (val == null) { // 如果不存在 ，则添加
            stringRedisTemplate.opsForValue().set(key, "1", 32, TimeUnit.DAYS);
            programming = key + "0001";

        } else {
            // 如果存在则格式化，并让val加1
            String s = leftPad(Integer.valueOf(val), 4, '0');
            stringRedisTemplate.opsForValue().increment(key);
            programming = key + s;
        }

        log.info(programming);

        //添加订单编号
        detailed.setProgramming(programming);

        // 入库
        detailedService.save(detailed);

        // 添加二维码
        Map<String, Object> map = new HashMap<>();
        map.put("id", detailed.getId());
        String code = GetQRCode.getCode(map);
        // 二维码
        detailed.setCode(code);

        detailedService.updateById(detailed);

        return new Result(null, Result.OK, "添加成功");

    }

    @ApiOperation(value = "修改")
    @PostMapping("/update")
    @ResponseBody
    public Result update(@RequestBody UpDetailedPO upDetailedPO){
        Detailed detailed = new Detailed();

        BeanUtils.copyProperties(upDetailedPO,detailed);

        boolean save = detailedService.updateById(detailed);

        if(save){
            return new Result(null,Result.OK,"修改成功");
        }{
            return new Result(null,Result.NULL,"修改失败");
        }

    }


    @ApiOperation(value = "出库")
    @PostMapping("/out")
    @ResponseBody
    public Result out(@RequestBody DeleteColourPO deleteColourPO){

        Detailed detailed = detailedService.getById(deleteColourPO.getId());

       detailed.setState(1);

        boolean save = detailedService.updateById(detailed);

        if(save){
            return new Result(null,Result.OK,"修改成功");
        }{
            return new Result(null,Result.NULL,"修改失败");
        }

    }


    @ApiOperation(value = "根据id删除")
    @PostMapping("/delete")
    @ResponseBody
    public Result delete(@RequestBody DeleteColourPO deleteColourPO){


        boolean save = detailedService.removeById(deleteColourPO.getId());

        if(save){
            return new Result(null,Result.OK,"删除成功");
        }{
            return new Result(null,Result.NULL,"删除失败");
        }

    }


    @ApiOperation(value = "通过id获取")
    @GetMapping("/getById")
    @ResponseBody
    public Result getById( Integer  id){
        Detailed detailed = detailedService.getById(id);

        if (detailed == null) {
            return new Result(null,Result.NULL,"不存在");
        }else {
            DetailedVO detailedVO = new DetailedVO();
            BeanUtils.copyProperties(detailed,detailedVO);

            Map<String,Object> data = new HashMap<>();
            data.put("detailed",detailedVO);
            return new Result(data,Result.OK,"请求成功");
        }


    }




    @ApiOperation(value = "获取入库列表")
    @GetMapping("/listInPage")
    @ResponseBody
    public Result listInPage(PagePO listPageColourPO){

        com.baomidou.mybatisplus.extension.plugins.pagination.Page page = new com.baomidou.mybatisplus.extension.plugins.pagination.Page(listPageColourPO.getPageNum(),listPageColourPO.getPageSize());

        com.baomidou.mybatisplus.extension.plugins.pagination.Page page1 = detailedService.page(page);

        List<Detailed> detaileds = page1.getRecords();
        List<DetailedVO> detailedVOS = new ArrayList<>();
        DetailedVO detailedVO = null;
        for (Detailed detailed : detaileds) {
            detailedVO = new DetailedVO();
            BeanUtils.copyProperties(detailed,detailedVO);
            detailedVOS.add(detailedVO);
        }

        Map data = new HashMap();
        data.put("total",page1.getTotal());
        data.put("size",page1.getSize());
        data.put("detaileds",detailedVOS);
        return new Result(data,Result.OK,"请求成功");
    }




    @ApiOperation(value = "获取出库列表")
    @GetMapping("/listOutPage")
    @ResponseBody
    public Result listOutPage(PagePO listPageColourPO){

        com.baomidou.mybatisplus.extension.plugins.pagination.Page page = new com.baomidou.mybatisplus.extension.plugins.pagination.Page(listPageColourPO.getPageNum(),listPageColourPO.getPageSize());

        QueryWrapper<Detailed> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("state",1);
        com.baomidou.mybatisplus.extension.plugins.pagination.Page page1 = detailedService.page(page,queryWrapper);

        List<Detailed> detaileds = page1.getRecords();
        List<DetailedVO> detailedVOS = new ArrayList<>();
        DetailedVO detailedVO = null;
        for (Detailed detailed : detaileds) {
            detailedVO = new DetailedVO();
            BeanUtils.copyProperties(detailed,detailedVO);
            detailedVOS.add(detailedVO);
        }

        Map data = new HashMap();
        data.put("total",page1.getTotal());
        data.put("size",page1.getSize());
        data.put("detaileds",detailedVOS);
        return new Result(data,Result.OK,"请求成功");
    }



    @ApiOperation(value = "获取管理列表")
    @GetMapping("/listAdminPage")
    @ResponseBody
    public Result listAdminPage(PagePO listPageColourPO){

        com.baomidou.mybatisplus.extension.plugins.pagination.Page page = new com.baomidou.mybatisplus.extension.plugins.pagination.Page(listPageColourPO.getPageNum(),listPageColourPO.getPageSize());

        QueryWrapper<Detailed> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("state",0);
        com.baomidou.mybatisplus.extension.plugins.pagination.Page page1 = detailedService.page(page,queryWrapper);

        List<Detailed> detaileds = page1.getRecords();
        List<DetailedVO> detailedVOS = new ArrayList<>();
        DetailedVO detailedVO = null;
        for (Detailed detailed : detaileds) {
            detailedVO = new DetailedVO();
            BeanUtils.copyProperties(detailed,detailedVO);
            detailedVOS.add(detailedVO);
        }

        Map data = new HashMap();
        data.put("total",page1.getTotal());
        data.put("size",page1.getSize());
        data.put("detaileds",detailedVOS);
        return new Result(data,Result.OK,"请求成功");
    }

//    @PostMapping("/getCodes")
//    public void downLoad(HttpServletResponse response, @RequestBody FileZipPO fileZipPO){
//        List files = new ArrayList();
//
//        Long[] ids = fileZipPO.getId();
//
//
//        List<Detailed> detaileds = detailedService.listByIds(ids);
//
//
//
//
//
//
//        List<String> strings = new ArrayList<>();
//
//        for (Detailed detailed : detaileds) {
//            strings.add(detailed.getCode());
//        }
//
//        files.addAll(strings);
//
//        String zipFilename = "File.zip";
//        File file = new File(zipFilename);
//        try {
//            file.createNewFile();
//            if (!file.exists()) {
//                file.createNewFile();
//            }
//            response.reset();
//            // 创建文件输出流
//            FileOutputStream fous = new FileOutputStream(file);
//            ZipOutputStream zipOut = new ZipOutputStream(fous);
//            int size = files.size();
//            for (int i = 0; i < size; i++) {
//                //单个文件的名称 文档的话后准就是.doc
//                String imgUrl = (String) files.get(i);
//                getFile(imgUrl ,zipOut,i + ".jpg");
//            }
//            zipOut.close();
//            fous.close();
//            // 以流的形式下载文件。
//            InputStream fis = new BufferedInputStream(new FileInputStream(file.getPath()));
//            byte[] buffer = new byte[fis.available()];
//            fis.read(buffer);
//            fis.close();
//            // 清空response
//            response.reset();
//            OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
//            response.setContentType("application/octet-stream");
//            // 如果输出的是中文名的文件，在此处就要用URLEncoder.encode方法进行处理
//            response.setHeader("Content-Disposition",
//                    "attachment;filename=" + new String(file.getName().getBytes("GB2312"), "ISO8859-1"));
//            toClient.write(buffer);
//            toClient.flush();
//            toClient.close();
//        } catch (Exception e) {
//            e.printStackTrace();
//        }  finally {
//            try {
//                File f = new File(file.getPath());
//                f.delete();
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
//        }
//    }
//
//

    private static String leftPad(int num, final int maxLen, char filledChar) {

        StringBuffer sb = new StringBuffer();
        String str = String.valueOf(num);

        for (int i = str.length(); i < maxLen; i++) {
            sb.append(filledChar);
        }

        return sb.append(str).toString();
    }

    /**
     * 获取文件流
     * @param url
     * @return
     * @throws IOException
     */
    private void getFile(String url ,ZipOutputStream zipOut ,String name) throws IOException{
        URL urlConet = new URL(url);
        HttpURLConnection con = (HttpURLConnection)urlConet.openConnection();
        con.setRequestMethod("GET");
        con.setConnectTimeout(4 * 1000);
        InputStream inStream = con .getInputStream();    //通过输入流获取图片数据
        ZipEntry entry = new ZipEntry(name);
        zipOut.putNextEntry(entry);
        byte[] buffer = new byte[inStream.available()];//available()是获取流中数据字节的最大长度
        int len = 0;
        while( (len=inStream.read(buffer)) != -1 ){
            zipOut.write(buffer, 0, len);
        }
        inStream.close();
    }



}